import {useState, useEffect} from 'react';
import {
    StyleSheet,
    View,
    Dimensions,
    Text,
    Platform,
    ScrollView,
    TouchableOpacity,
    TextInput,
    PermissionsAndroid,
} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import AllStyle from '../../../style';
import * as React from 'react';
import {HeaderTitle} from '../../../componet/settingComponent/HeaderTitle';
import {MapView, AMapSdk, MapType, Marker, Polyline} from 'react-native-amap3d';
import {init, Geolocation} from 'react-native-amap-geolocation';
import {Toast} from '../../../utils/Toast';
import {BottomButton} from '../../../componet/settingComponent/BottomButton';
import {getDistance} from '../../../utils';
//获取位置权限
PermissionsAndroid.requestMultiple([
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
]).catch(err => {
    Toast.showWarning(err.toString());
}).then(res => {

});
//位置初始化
init({
    ios: '1be169e585123b6e68a91d9aa355ae14',
    android: 'fd68d9ef3201d3ba7376ae6f89673904',
}).then(res => {
}).catch(err => {
    Toast.showWarning(err);
});
//地图位置初始化
AMapSdk.init(
    Platform.select({
        android: 'fd68d9ef3201d3ba7376ae6f89673904',
        ios: '1be169e585123b6e68a91d9aa355ae14',
    }),
);
let mapView: MapView;

export function LocationListScreen(props) {
   // const [location, setLocation] = useState({});
    const [locations, setLocations] = useState(props.route.params.locations ? props.route.params.locations : []);
    useEffect(() => {
        //console.log(JSON.stringify(props.route.params.locations),'props.locations')
        initLocation();
    }, []);
    const back = () => {
        props.navigation.goBack();
    };
    // const goto = () => {
    //
    // };
    const initLocation = () => {
        let locationCur= {}
        //监听定位
        Geolocation.getCurrentPosition(({coords}) => {
            //console.log(coords);
            let {latitude, longitude} = coords;
            locationCur.longitude = longitude.toFixed(6);
            locationCur.latitude = latitude.toFixed(6);
            //console.log(locationCur,'locationCur');
            //setLocation({locationCur})
            let rangeList=[];

            if (locations.length > 0) {
                //循环算出每个打卡地点，与当前位置的距离
                for (let i=0;i<locations.length;i++){
                    let range= getDistance(locationCur.longitude,locationCur.latitude,locations[i].placeLatitude,locations[i].placeLatitude)
                    console.log(range,'range')
                    rangeList.push({index:i,range:range})
                }
                //找到最近的签到点
                rangeList.sort((a, b)=>{
                    return a.range-b.range
                })
                console.log(rangeList,'rangeList');
                //移动至最近的标记点
                mapView?.moveCamera(
                    {
                        tilt: 0,
                        bearing: 0,
                        zoom: 16,
                        target: {
                            latitude: parseFloat(locations[rangeList[0].index].placeLatitude),
                            longitude: parseFloat(locations[rangeList[0].index].placeLongitude),
                        },
                    },
                    1000,
                );
            }

        })

    };
    return (
        <SafeAreaView edges={['top', 'left', 'right', 'bottom']} style={{flex: 1, backgroundColor: '#ffffff'}}>
            <View style={AllStyle.container}>
                <HeaderTitle goBack={() => back()} headtitle={props.route.params.title}></HeaderTitle>
                <View style={{flex: 1}}>
                    <MapView
                        ref={(ref: MapView) => (mapView = ref)}
                        myLocationEnabled={true}
                        onLoad={(nativeEvent) => {
                            console.log(nativeEvent);
                        }}
                        onCameraIdle={({nativeEvent}) => {
                            //this.set(nativeEvent.cameraPosition.target.latitude.toFixed(6), nativeEvent.cameraPosition.target.longitude.toFixed(6));
                        }}
                    >
                        {locations.map(item => {
                            return (
                                <Marker
                                    key={item.placeLatitude}
                                    draggable
                                    position={
                                        {latitude: item.placeLatitude, longitude: item.placeLongitude}
                                    }
                                    onDragEnd={({nativeEvent}) =>
                                        alert(`onDragEnd: ${nativeEvent.latitude}, ${nativeEvent.longitude}`)
                                    }
                                />
                            );

                        })}
                    </MapView>
                </View>
                <BottomButton title='返回' click={() => {
                    back();
                }}></BottomButton>
            </View>
        </SafeAreaView>

    );
}

const style = StyleSheet.create({
//样式
});
